package com.smallkingson.ylib.view.utils;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.graphics.Point;
import android.os.Build;


/**
 * Created by yorun on 2017/4/18.
 */

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PointAnimator implements ValueAnimator.AnimatorUpdateListener, Animator.AnimatorListener {

    private Point[] points;

    int currentStartIndex;

    long duration = 500;

    AnimatorListener animatorListener;

    private PointAnimator(Point[] points) {
        this.points = points;
    }

    public PointAnimator setAnimatorListener(AnimatorListener animatorListener) {
        this.animatorListener = animatorListener;
        return this;
    }

    public void start() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
        valueAnimator.setDuration(duration);
        valueAnimator.addUpdateListener(this);
        valueAnimator.addListener(this);
        valueAnimator.start();
    }

    public PointAnimator setDuration(long duration) {
        this.duration = duration/(points.length-1);
        return this;
    }

    public static PointAnimator ofPoint(Point... point) {
        if (point.length < 2) {
            throw new IllegalArgumentException();
        }
        PointAnimator pointAnimator = new PointAnimator(point);
        return pointAnimator;
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float animatedFraction = animation.getAnimatedFraction();
        int x = (int) (points[currentStartIndex].x + animatedFraction * (points[currentStartIndex + 1].x - points[currentStartIndex].x) + 0.5f);
        int y = (int) (points[currentStartIndex].y + animatedFraction * (points[currentStartIndex + 1]
                .y - points[currentStartIndex].y) + 0.5f);
        this.animatorListener.onAnimationUpdate(new Point(x, y));
    }

    @Override
    public void onAnimationStart(Animator animation) {
    }

    @Override
    public void onAnimationEnd(Animator animation) {
        currentStartIndex++;
        if (currentStartIndex < points.length - 1) {
            start();
        }else{
            this.animatorListener.onAnimationEnd();
        }
    }
    @Override
    public void onAnimationCancel(Animator animation) {
    }
    @Override
    public void onAnimationRepeat(Animator animation) {
    }

    public static interface AnimatorListener {

        void onAnimationUpdate(Point point);

        void onAnimationEnd();
    }

}
